
/**
 * 封装uni.request请求
 */
class YZRequest{
  //拦截器定义
  interceptors = {
    request: config => config,
    response: response => response
  }
  
  constructor(baseUrl){
    this.baseUrl = baseUrl
  }
  
  request(options){
    options.url = this.baseUrl + options.url
    //请求前拦截器拦截请求参数，进行参数加工
    if(this.interceptors.request){
      this.interceptors.request(options)
    }
    //开始请求接口
    return new Promise((resolve,reject)=>{
      uni.request({
        ...options,
        success: res=>{
          //通过isSuccess来判断服务器是否响应
          res.isSuccess = true
          res.config = options
          //拦截器处理响应结果
          if(this.interceptors.response){
            res = this.interceptors.response(res)
          }
          resolve(res)
        },
        fail:err=>{
          //通过isSuccess来判断网络问题
          err.isSuccess = false
          // 拦截器处理结果
          if(this.interceptors.response){
            err = this.interceptors.response(err)
          }
          reject(err)
        }
      })
    })
  }
  
  get(url, data={}){
    return this.request({url, data, method:'GET'})
  }
  post(url, data={}){
    return this.request({url, data, method:'POST'})
  }
  put(url, data={}){
    return this.request({url, data, method:'PUT'})
  }
  delete(url, data={}){
    return this.request({url, data, method:'DELETE'})
  }
}
export default YZRequest